'use strict';
let gulp = require('gulp');
let babel = require('gulp-babel');
//let fs=require("fs");
let plumber = require('gulp-plumber');
//let path = require("path");
//let less=require("gulp-less");
//let destChmod=require("./gulp-dest-chmod");
//let webpack=require("gulp-webpack");
//let named = require("vinyl-named");
let ZPack = require('./z-pack');
let changed = require('gulp-changed');

let babelOpt = {
    'presets': [
        /* "latest", */
		'react',
		/* "stage-0"  */
	],
	'plugins': [
		'babel-plugin-transform-es2015-modules-commonjs',
		'babel-plugin-transform-export-extensions',
		'babel-plugin-transform-class-properties',
		'transform-decorators-legacy',
		'babel-plugin-transform-object-rest-spread',
		['import', { 'libraryName': 'antd', 'style': true }]
	],
	'compact': 'false'
};

let zpackOpt = {
	avoidError: true,
	babel: babelOpt,
	hosts: {
		[__dirname + '/view']: '//127.0.0.1:3001/',
		[__dirname + '/node_modules']: '//127.0.0.1:3001/node_modules'
	},
	external: [
		'babel-polyfill', 
		'jQuery', 
		'react', 
		'react-dom', 
		'antd'
	],
	lessVars: {
		// '@primary-color': '#ff0000'
	}
};

gulp.task('stub', function() {
	return gulp.src('z-pack/ZPackStub.js')
		.pipe(gulp.dest('build/view'));
});

gulp.task('front', [], function() {
	return gulp.src(['view/**/*', '!view/**/*.d.ts'])
		.pipe(changed('build/view'))
		.pipe(plumber())		
		.pipe(ZPack(zpackOpt))
		.pipe(plumber())
		.pipe(gulp.dest('build/view'));
});

gulp.task('back', function() {
	return gulp.src('src/**/*.js')
		.pipe(plumber())
		.pipe(babel(babelOpt))
		.pipe(gulp.dest('build/src'));
});

gulp.task('watch', ['front', 'back', 'stub'], function() {
	gulp.watch(['view/**/*'], ['front']);
	gulp.watch(['src/**/*.js'], ['back']);
	gulp.watch(['z-pack/ZPackStub.js'], ['stub']);
});


gulp.task('library', function() {
	return gulp.src([
			...[
				//'prop-types',
				//'react',
				//'antd',
				//'react-custom-scrollbars',
				'numeric'
			].map(e => require.resolve(e)),
			//'node_modules/antd/lib/*/style/*.js'
		], { base: 'node_modules' })
		.pipe(ZPack(Object.assign(zpackOpt, { recursive: true })))
		.pipe(gulp.dest('build/node_modules'));
});

gulp.task('lib', ['library']);